package dryven.view.engine.expression.nodelisters;

import java.util.LinkedList;
import java.util.List;

import dryven.reflection.Method;
import dryven.reflection.MethodIterator;
import dryven.reflection.MethodListener;
import dryven.reflection.TypeRef;
import dryven.view.engine.expression.ExpressionNode;
import dryven.view.engine.expression.nodetypes.MethodCallNode;

public class ObjectNodeLister implements NodeLister {

	private ExpressionNodeFactory _factory;
	private List<ExpressionNode> _nodes;
	private TypeRef _type;
	
	public ObjectNodeLister(TypeRef t, ExpressionNodeFactory factory) {
		_factory = factory;
		_type = t;
	}
	
	@Override
	public Iterable<ExpressionNode> getChildNodes() {
		_nodes = new LinkedList<ExpressionNode>();
		MethodIterator it = new MethodIterator(new MethodListener() {
			@Override
			public void methodFound(Method m) {
				if(m.getParameterType().length==0 && m.getReturnType()!=null && m.isPublic()) {
					addMethodNode(m);
				}
			}
		},_type);
		it.iterate();
		List<ExpressionNode> nodes = _nodes;
		_nodes = null;
		return nodes;
	}

	protected void addMethodNode(Method m) {
		String name = m.getName();
		if(name.toLowerCase().startsWith("get")) {
			name = name.substring(3);
		} else if(name.toLowerCase().startsWith("is")) {
			name = name.substring(2);
		}
		if(Character.isUpperCase(name.charAt(0))) {
			name = name.substring(0, 1).toLowerCase()+name.substring(1);
		}
				
		TypeRef t = m.getReturnType();
		NodeLister nodeLister = _factory.create(t);
		ExpressionNode node = new MethodCallNode(name, m, nodeLister);
		_nodes.add(node);
	}

	@Override
	public boolean allowsWildChar() {
		return false;
	}

	@Override
	public ExpressionNode createWildCharNode(String name) {
		return null;
	}
}
